package eteam.aps.common.exceptions.handler;


import eteam.aps.common.R;
import eteam.aps.common.exceptions.BusinessException;
import eteam.aps.common.exceptions.DelimiterException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

/**
 * 全局异常处理器
 *
 * @author WMT
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理业务异常
     */
    @ExceptionHandler({BusinessException.class, DelimiterException.class})
    public R<Void> handleCoolSharkServiceException(Exception e) {
        log.error("出现业务异常，业务错误码={}", HttpStatus.BAD_REQUEST, e);
        return R.failed(HttpStatus.BAD_REQUEST.value(), e.getMessage());
    }

    /**
     * 处理绑定异常（通过Validation框架验证请求参数时的异常）
     */
    @ExceptionHandler(BindException.class)
    public R<Void> handleBindException(BindException e) {
        log.error("验证请求数据时出现异常", e);
        String message = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();
        return R.failed(HttpStatus.BAD_REQUEST.value(), message);
    }

    /**
     * 数据库，异常处理
     */
    @ExceptionHandler(value = DuplicateKeyException.class)
    public R duplicateKeyErrorHandler(DuplicateKeyException ex) {
        log.error("出现业务异常，业务错误码={}", HttpStatus.BAD_REQUEST, ex);
        return R.failed(HttpStatus.BAD_REQUEST.value(), "数据库已存在重复数据");
    }

    /**
     * 处理系统（其它）异常
     */
    @ExceptionHandler({Throwable.class})
    public R<Void> handleSystemError(Throwable e) {
        log.error("出现业务异常，业务错误码={}", HttpStatus.BAD_REQUEST, e);
        return R.failed(HttpStatus.INTERNAL_SERVER_ERROR.value(), "服务器异常");
    }
}
